import { MedusaResponse, MedusaStoreRequest, refetchEntity, } from "@medusajs/framework/http" import { MedusaError } from "@medusajs/framework/utils" import { runCoreWorkflow } from "../../../../../modules/paypal/utils/core-workflow" type CreatePaymentSessionBody = { provider_id: string data?: Record } /** Fields returned when the request carries no explicit `fields` query. */ const defaultPaymentCollectionFields = [ "id", "currency_code", "amount", "*payment_sessions", ] /** * POST /store/payment-collections/:id/payment-sessions — create a payment * session via the core workflow and return the refreshed collection. */ export async function POST(req: MedusaStoreRequest, res: MedusaResponse) { const collectionId = req.params.id const { provider_id, data } = req.body as CreatePaymentSessionBody if (!provider_id || typeof provider_id !== "string") { throw new MedusaError( MedusaError.Types.INVALID_DATA, "provider_id is required to create a payment session" ) } try { await runCoreWorkflow(req.scope, "create-payment-sessions", { payment_collection_id: collectionId, provider_id, customer_id: req.auth_context?.actor_id, data, }) } catch (error) { // A failed core workflow rejects with the step's error, which is not // always an `Error` instance (a plain `{ message }` object surfaces as // "[object Object]" otherwise). const message = (error as { message?: unknown } | null)?.message != null ? String((error as { message?: unknown }).message) : String(error) throw new MedusaError( MedusaError.Types.UNEXPECTED_STATE, `Failed to create payment session for provider '${provider_id}': ${message}` ) } const paymentCollection = await refetchEntity({ entity: "payment_collection", idOrFilter: collectionId, scope: req.scope, fields: req.queryConfig?.fields ?? defaultPaymentCollectionFields, }) res.status(200).json({ payment_collection: paymentCollection, }) }